set -e


bin=$(dirname "$0")
bin=$(
  cd "$bin"
  pwd
)

. meta-lib-static/env/.env
echo "[*setup*] waiting metabase server...."
while ! timeout 1 bash -c "echo > /dev/tcp/localhost/${METABASE_SERVER_PORT}" ; do 
  sleep 10 
  echo "[*setup*] waiting metabase server...."
done
sleep 10

DE_STATIC_DIR=$ACCESS_STATIC_DIR

unameOut="$(uname -s)"
case "${unameOut}" in
    Linux*)     OS=linux;;
    Darwin*)    OS=macos;;
esac

JQ=$DE_STATIC_DIR/$OS/jq-*

ONE_NODE=$(echo $METABASE_SERVER_HOSTS | cut -d, -f1)
API_URL=http://$ONE_NODE:$METABASE_SERVER_PORT/api

echo -ne   "  [*setup*] API_URL: $API_URL\n"
JSON='Content-Type: application/json'

echo -ne "\n  [*setup*] 1. create user $UNAME...\n"
SID=$(curl -XPOST -H "$JSON" $API_URL/session -d $'{"username":"metabase@metabase.org","password":"metabase123!"}' | $JQ -r '.id')
UNAME=$METABASE_SERVER_USERNAME
UPASS=$METABASE_SERVER_PASSWORD
curl -XPOST -H "$JSON" -H "X-Metabase-Session: $SID" $API_URL/user -d $'{"first_name":"metabase","last_name":"metabase","email":"'${UNAME}'","password":"'${UPASS}'"}'
curl -XPUT -H "$JSON" -H "X-Metabase-Session: $SID" $API_URL/user/2 -d $'{"is_superuser":true}'
curl -XDELETE -H "X-Metabase-Session: $SID" $API_URL/user/1 
SID=$(curl -XPOST -H "$JSON" $API_URL/session -d $'{"username":"'${UNAME}'","password":"'${UPASS}'"}' | $JQ -r '.id')

echo -ne "\n  [*setup*] 2. add hive datasource...\n"
HIVE_NODE=$(echo $METABASE_SERVER_HIVE_NODES | cut -d, -f1)
HIP=$(echo $HIVE_NODE | cut -d: -f1)
HPORT=$(echo $HIVE_NODE | cut -d: -f2)
HUNAME=${METABASE_SERVER_HIVE_USERNAME}
HUPASS=${METABASE_SERVER_HIVE_PASSWORD}
HSCHEMA=${METABASE_SERVER_HIVE_SCHEMA}
DS_DETAILS=$'{"host":"'${HIP}'","port":"'${HPORT}'","dbname":"'${HSCHEMA}'","user":"'${HUNAME}'","password":"'${HUPASS}'","jdbc-flags":";auth=noSasl"}'
curl -XPOST -H "$JSON" -H "X-Metabase-Session: $SID" $API_URL/database -d $'{"name":"'${HSCHEMA}'","engine":"sparksql","details":'${DS_DETAILS}'}'

echo -ne "\n [*setup*] setup finished!\n"
